<script setup lang="ts">
 import { uploadAPI } from '@/apis/common';
import { createRentAPI, delEnterpriseAPI, delRentAPI, getEnterpriseListAPI, getRentBuildListAPI, getRentListAPI, outRentAPI } from '@/apis/enterprise';
  import type { Datum, Enterprise, EnterpriseListParams, RentBuilding, RentParams } from '@/types/enterprise';
import { dayjs, ElMessage, ElMessageBox, type FormInstance, type FormRules, type UploadRawFile, type UploadRequestOptions, type UploadUserFile } from 'element-plus';
  import { ref, watch } from 'vue';

  const params = ref<EnterpriseListParams>({
    page: 1,
    pageSize:10,
    name: ''
  })
  const list = ref<EnterpriseWithRent[]>([])
  const total = ref(0)

  const getList = async () => {
    const res =  await getEnterpriseListAPI(params.value)
    console.log('qiye', res)
    list.value = res.data.rows.map(item=>({
      ...item,
      rentList: []
    }))
    total.value = res.data.total
  }

  getList()

  const onSearch = () => {
    // 重置页数
    params.value.page = 1
    getList()
  }

  // 删除企业
const delEnterprise = async(id: string) => {
  ElMessageBox.confirm('此操作将永久删除, 是否继续?', '温馨提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async() => {
    // 删除
    await delEnterpriseAPI(id)
    ElMessage.success('删除成功')
    getList()
  }).catch(() => {})
}
// **********添加合同**********

// 前端自定义类型，为了给每行加上合同数据
interface EnterpriseWithRent extends Enterprise {
  rentList: Datum[]
}

// 可租赁楼宇列表
const buildList = ref<RentBuilding[]>([]) 
// dialog弹窗控件
const rentDialogVisible = ref(false)
// 添加合同
const addRent = async(id : number) => {
  dialogValue.value = 0
  // 打开弹窗
  rentDialogVisible.value = true
  // 获取可租赁楼宇列表
  const res = await getRentBuildListAPI()
  // console.log('res', res);
  buildList.value = res.data
  // 保存企业id，用于添加合同
  rentForm.value.enterpriseId = id
}
const closeRent = () => {
  // 关闭弹窗
  rentDialogVisible.value = false
  addFormRef.value?.resetFields()
  timeArr.value = []
  fileList.value = []
  // 重置表单数据
  rentForm.value = initRentForm()
}

// 禁用日期的范围
const disableDate = (time: Date) => {
  return time.getTime() < Date.now() - 8.64e7
}
const renewDisableDate = (time: Date) => {
  // 将rentForm.value.startTime转回时间戳
  const startTime = dayjs(rentForm.value.startTime).valueOf()
  // 禁用日期的范围 是上个合同的日期+1天
  return time.getTime() < startTime + 8.64e7
}


const timeArr = ref<string[]>([])
watch(timeArr,(val)=>{
  if(val){
    rentForm.value.startTime = val[0]
    rentForm.value.endTime = val[1]
  }else{
    rentForm.value.startTime = ''
    rentForm.value.endTime = ''
  }
},{deep: true})

const addFormRef = ref<FormInstance>()
// 上传文件
const onUploadContract = async (options: UploadRequestOptions) => {
  const fd = new FormData()
  fd.append('file', options.file)
  fd.append('type', 'contract')
  const res =  await uploadAPI(fd)
  console.log('contract',res)
  rentForm.value.contractUrl = res.data.url
  rentForm.value.contractId = res.data.id
  addFormRef.value?.validateField('contractId')
  return res.data.url
}

// 删除上传的合同
const removeContract = () => {
  rentForm.value.contractUrl = ''
  rentForm.value.contractId = undefined
  addFormRef.value?.validateField('contractId')
}


// 表单数据默认值，每次调用，都返回一个新对象
const initRentForm = () => {
  return {
    buildingId: undefined,
    contractId: undefined,
    contractUrl: '',
    endTime: '',
    enterpriseId: undefined,
    startTime: '',
    type: 0,
  }
}

// 表单数据
const rentForm = ref<RentParams>(initRentForm())

const fileList = ref<UploadUserFile[]>([])
// 表单验证
const rentRules = ref<FormRules<RentParams>>({
  buildingId: [
    { required: true, message: '请选择楼宇', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择租赁日期', trigger: 'blur' }
  ],
  contractId: [
    { required: true, message: '请上传合同文件' }
  ]
})
// 限制上传大小
const beforeUpload = (rawFile: UploadRawFile) => {
  const isLt5M = rawFile.size / 1024 / 1024 < 5
  if (!isLt5M) {
    ElMessage.error('上传图片大小不能超过5M')
    return false
  } else {
    return true
  }
}
// 添加合同确认
const addRentConfirm = async () => {
  try {
    // 表单验证
    await addFormRef.value?.validate()
    // 提交数据
    await createRentAPI(rentForm.value)
    // 提示
    ElMessage.success('添加成功')
    
    // 局部刷新列表，不重新请求数据
    const qiye = list.value.find(item => item.id === rentForm.value.enterpriseId)
    // 调用展开行的函数
    onExpandChange(qiye!)
    // 关闭弹窗
    closeRent()
  } catch {
    
  }
}

// 展开行触发时候
const onExpandChange = async(row: EnterpriseWithRent) => {
  // console.log('当前行被展开', row.id);
  const res = await getRentListAPI(row.id)
  // console.log('rentlist', res)
  row.rentList = res.data
}

// 退租
const outRent = (row: Datum) => {
  ElMessageBox.confirm('此操作将不可逆, 是否继续?', '温馨提示', {
    confirmButtonText: '退租',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async() => {
    console.log('id', row.id)
    await outRentAPI(row.id)
    row.status = 3
    ElMessage.success('退租成功')
  }).catch(() => {})
}

// 删除合同
const delRent = (sonRow: Datum,row: EnterpriseWithRent) =>{
  ElMessageBox.confirm('此操作将永久删除合同, 是否继续?', '温馨提示', {
    confirmButtonText: '删除',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async() => {
    // console.log('id', id)
    // 后端接口删除
    await delRentAPI(sonRow.id)
    // 前端过滤，为了不整个刷新列表，这样性能高
    row.rentList = row.rentList.filter(item => item.id !== sonRow.id)
    ElMessage.success('删除成功')
  }).catch(() => {})
} 
// 弹窗类型
const dialogValue = ref(0)
const buildingName = ref<string>('')
// 续费合同
const renewRent = async (row:EnterpriseWithRent,sonRow: Datum) => {
  console.log('row',row)
  console.log('sonRow',sonRow)
  console.log('list',list.value)
  dialogValue.value = 1
  // 打开弹窗
  rentDialogVisible.value = true
  // 将sonRow.endTime转回时间戳
  const endTime = dayjs(sonRow.endTime).valueOf() + 8.64e7
  // 再将endTime转回日期格式
  // dayjs(endTime).format('YYYY-MM-DD')
  rentForm.value = {
    buildingId: +sonRow.buildingId,
    contractId: undefined,
    contractUrl: '',
    endTime: '',
    enterpriseId: row.id,
    startTime: dayjs(endTime).format('YYYY-MM-DD'),
    type: 1,
  }
  buildingName.value = sonRow.buildingName as string
  console.log('rentForm.value',rentForm.value)
}
</script>


<template>
  <div class="building-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <div class="search-label">企业名称：</div>
      <el-input clearable placeholder="请输入内容" v-model="params.name" @clear="onSearch" class="search-main" />
      <el-button type="primary" @click="onSearch">查询</el-button>
    </div>
    <div class="create-container">
      <el-button type="primary" @click="$router.push('/exterpriseAdd')">添加企业</el-button>
    </div>
    <!-- 表格区域 -->
    <div class="table">
      <el-table style="width: 100%" :data="list" @expand-change="onExpandChange" row-key="id">
          <!-- type="expand" 显示一个可展开的按钮 -->
          <el-table-column type="expand">
            <template #default="{ row  }">
              <el-table :data="row.rentList">
                <el-table-column label="租赁楼宇" width="320" prop="buildingName" />
                <el-table-column label="租赁起止时间" prop="startTime">
                  <template #default="{ row }">
                    {{ row.startTime }} 至 {{ row.endTime }}
                  </template>
                </el-table-column>
                <el-table-column label="合同状态" prop="status">
                  <template #default="{ row }">
                    <el-tag v-if="row.status === 0" type="info">待生效</el-tag>
                    <el-tag v-if="row.status === 1" type="success">生效中</el-tag>
                    <el-tag v-if="row.status === 2" type="warning">已到期</el-tag>
                    <el-tag v-if="row.status === 3" type="danger">已退租</el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="180">
                  <template #default="{ row: sonRow }">
                    <el-button size="small" link type="primary" @click="renewRent(row,sonRow)" :disabled="sonRow.renewFlag === 0">续租</el-button>
                    <el-button size="small" link type="primary" @click="outRent(sonRow)" :disabled="sonRow.status === 3">退租</el-button>
                    <el-button size="small" link type="primary" @click="delRent(sonRow,row)" :disabled="sonRow.status !== 3">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </template>
          </el-table-column>
        <el-table-column type="index" label="序号" width="120" />
        <el-table-column prop="name" label="企业名称" width="320" />
        <el-table-column prop="contact" label="联系人" />
        <el-table-column prop="contactNumber" label="联系电话" />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button size="small" link type="primary" @click="addRent(scope.row.id)">添加合同</el-button>
            <el-button size="small" link type="primary" @click="$router.push(`/exterpriseDetail/${ scope.row.id }`)">查看</el-button>
            <el-button size="small" link type="primary" @click="$router.push(`/exterpriseAdd/${scope.row.id}`)">编辑</el-button>
            <el-button 
            size="small" link type="primary"
            @click="delEnterprise(scope.row.id)"
            :disabled="!!scope.row.existContractFlag"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page-container">
      <el-pagination
        :total="total" 
        layout="total, sizes, prev, pager, next, jumper"
        :page-sizes="[2, 5, 10, 20, 100]"
        v-model:page-size="params.pageSize"
        v-model:current-page="params.page"
        @change="getList()"
      />
    </div>
    <el-dialog :title="dialogValue === 1 ? '续租合同' : '添加合同'" width="600px" v-model="rentDialogVisible" @close="closeRent">
      <div class="form-container">
        {{ timeArr }}
        <el-form ref="addFormRef" :model="rentForm" :rules="rentRules" label-position="top">
          <el-form-item label="租赁楼宇" prop="buildingId">
            <el-select v-if="dialogValue === 0" v-model="rentForm.buildingId" placeholder="请选择">
              <el-option v-for="item in buildList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
            <el-input v-if="dialogValue === 1" v-model="buildingName"  disabled></el-input>
          </el-form-item>
          <el-form-item label="租赁起止日期" prop="endTime">
            <el-date-picker v-if="dialogValue === 0" :disabled-date="disableDate" v-model="timeArr" type="daterange" range-separator="至" start-placeholder="开始日期"
              end-placeholder="结束日期" value-format="YYYY-MM-DD" />
            <div v-if="dialogValue === 1" style="display: flex;gap: 20px; ">
              <el-input  v-model="rentForm.startTime" disabled></el-input>
              <div>-</div>
              <el-date-picker type="date" :disabled-date="renewDisableDate" v-model="rentForm.endTime" format="YYYY-MM-DD" clearable></el-date-picker>
            </div>
          </el-form-item>
          <el-form-item label="租赁合同" prop="contractId">
            <el-upload 
              accept=".doc, .pdf"
              :http-request="onUploadContract"
              :on-remove="removeContract"
              :before-upload="beforeUpload"
              v-model:file-list="fileList"
            >
              <el-button size="small" type="primary" plain>上传合同文件</el-button>
              <template #tip>
                <div class="el-upload__tip">支持扩展名：.doc .pdf, 文件大小不超过5M</div>
              </template>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
           <el-button size="small" @click="closeRent">取 消</el-button>
           <el-button size="small" type="primary" @click="addRentConfirm">确 定</el-button>
        </div>
        {{ rentForm }}
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.building-container {
  padding: 20px;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, .9);
  ;
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}

.create-container {
  margin: 10px 0px;
}

.page-container {
  padding: 4px 0px;
  display: flex;
  justify-content: flex-end;
}

.form-container {
  padding: 0px 80px;
}
</style>